package com.cxh.controller.car;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.cxh.base.BaseController;
import com.cxh.entity.CarDetailBaseInfo;
import com.cxh.util.CommonUtility;
import com.cxh.util.DateUtility;
import com.cxh.util.json.JSONUtil;

import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 类说明：学生表 
 * @author  YangHL
 * @date  2018-10-15 17:20:09
 */
@Controller
@RequestMapping(value = "/controller/carDetailBaseInfo")
public class CarDetailBaseInfoController extends BaseController {

    /**
     * 方法说明：进入页面
     * @author  YangHL
     * @date  2018-10-15 17:20:09
     */
    @RequestMapping(value = "/list")
    public ModelAndView list (HttpServletRequest request, HttpServletResponse response){
        ModelAndView model =  new ModelAndView();
        model.setViewName("manager/carDetailBaseInfo/list");
        return model;
    }

    /**
     * 方法说明：获得表格数据
     * @author  YangHL
     * @date  2018-10-15 17:20:09
     */
    @RequestMapping(value = "/showList")
    @ResponseBody
    public String showList (HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        String json="";
        //获得  页码数
        Integer page=CommonUtility.isEmpty(params.get("page"))?1:Integer.parseInt(params.get("page")+"");
        //获得 每页的行数
        Integer limit=CommonUtility.isEmpty(params.get("limit"))?10:Integer.parseInt(params.get("limit")+"");
        //设置 分页参数
        PageHelper.startPage(page,limit);
        //调用 查询方法
        List<CarDetailBaseInfo> carDetailBaseInfoList=carDetailBaseInfoService.loadPageList(params);
        //处理数据
        PageInfo<CarDetailBaseInfo> pageInfo=new PageInfo<CarDetailBaseInfo>(carDetailBaseInfoList);
        try {
            //转换 时间格式/并将数据转换成json字符串
            JsonConfig jsonConfig = JSONUtil.getJsonConfig(DateUtility.DateFormat1);
            json= JSONUtil.toLayUIJSONAll(pageInfo.getTotal(),pageInfo.getList(), jsonConfig);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 方法说明：进入编辑页面
     * @author  YangHL
     * @date  2018-10-15 17:20:09
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response){
        //获得要修改数据的Id
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        ModelAndView model=new ModelAndView();
        CarDetailBaseInfo carDetailBaseInfo=new CarDetailBaseInfo();
        try {
            //判断是 修改  还是 新增
            if (!CommonUtility.isEmpty(entityId)&&entityId>0) {
                carDetailBaseInfo = carDetailBaseInfoService.selectByPrimaryKey(entityId);
                // 进行数据准备
                model.addObject("carDetailBaseInfo",carDetailBaseInfo);
            }
            //返回视图位置
            model.setViewName("manager/carDetailBaseInfo/form");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    /**
     * 方法说明：保存/修改
     * @author  YangHL
     * @date  2018-10-15 17:20:09
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public String save (HttpServletRequest request, HttpServletResponse response,@RequestParam  Map<String,Object> jsonMap,CarDetailBaseInfo carDetailBaseInfoSave){
        //执行状态（0成功；1失败）
        int flag=0;
        int entityId=CommonUtility.isEmpty(jsonMap.get("entityId"))?0:Integer.parseInt(jsonMap.get("entityId")+"");
        //进行 修改
        if(entityId>0){
            CarDetailBaseInfo carDetailBaseInfo=carDetailBaseInfoService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(carDetailBaseInfo)){
            	carDetailBaseInfoSave.setId(entityId);
                try {
                    //修改
                    carDetailBaseInfoService.updateByPrimaryKey(carDetailBaseInfoSave);
                    //operationLog(request, "修改用户" + user.getLoginName(), TableConstants.LOG_TYPES_EDIT);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }else{
                flag=1;
            }
        }else{
            //进行数据添加
            //CarDetailBaseInfo carDetailBaseInfo=new CarDetailBaseInfo();

            try {
                //新增
                carDetailBaseInfoService.insert(carDetailBaseInfoSave);
                //operationLog(request, "添加用户" + user.getLoginName(), TableConstants.LOG_TYPES_ADD);
            }catch (Exception e) {
                flag = 1;
                e.printStackTrace();
            }
        }

        return flag+"";
    }

    /**
     * 方法说明：删除
     * @author  YangHL
     * @date  2018-10-15 17:20:09
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete (HttpServletRequest request, HttpServletResponse response){
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        //执行状态（0成功；1失败）
        int flag = 0;
        if(entityId>0){
            CarDetailBaseInfo carDetailBaseInfo = carDetailBaseInfoService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(carDetailBaseInfo)){
                //carDetailBaseInfo.setIsDel(0);
                try {
                    carDetailBaseInfoService.updateByPrimaryKey(carDetailBaseInfo);
                    //operationLog(request, "删除用户" + user.getLoginName(), TableConstants.LOG_TYPES_DEL);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }
        }
        return flag+"";
    }
    
    @RequestMapping("/uploadImg")
    @ResponseBody
    public HashMap<String, Object> uploadImg(MultipartFile file,HttpServletRequest request){
    	String path = request.getContextPath();
    	
    	HashMap<String, Object> hashMap = new HashMap<String,Object>();
    	HashMap<String, Object> dataMap = new HashMap<String,Object>();
    	
    	// 判断文件是否为空
        if (!file.isEmpty()) {
            try {
            	//得到文件分隔符
                String separator = File.separator;
                String picPath2 = System.getProperty("user.dir").replace("bin","webapps"+path)+ File.separator;
                String directory = picPath2 + "common/img" + separator;
                String newPicName = file.getName()+System.currentTimeMillis();
                if (file.getSize() != 0) {
                	String originalFileNameLeft = file.getOriginalFilename();
                    // 新的图片名称
                    newPicName +=  originalFileNameLeft.substring(originalFileNameLeft.lastIndexOf("."));
                    // 新图片，写入磁盘
                    File f = new File(directory, newPicName);
                    if (!f.exists()) {
                        // 先创建文件所在的目录
                        f.getParentFile().mkdirs();
                    }
                    file.transferTo(f);
                    hashMap.put("code", "0");
                	hashMap.put("msg", "上传成功");
                	dataMap.put("src", newPicName);
                	hashMap.put("data", dataMap);
                }
                return hashMap;
            } catch (Exception e) {
                e.printStackTrace();
                hashMap.put("code", "0");
            	hashMap.put("msg", "上传失败，已存在该图片");
            	dataMap.put("src", "");
            	hashMap.put("data", dataMap);
            	return hashMap;
            }
        }
        return hashMap;
    }


}
